'use strict';
const jwt = require('jwt-simple')
const crypto = require('crypto')
const db = uniCloud.database()
const loginConfig = {
		
	  }
exports.main = async(event,context){
		// 封装数据
	let data = {
			appid: loginConfig.appid,
			secret: loginConfig.secret,
			js_code: event.code,
			grant_type: "authorization_code"
		}
		// 向微信服务器提交code+appid+secret,返回openid和session_key
	const res = await uniCloud.httpclient.request('https://api.weixin.qq.com/sns/jscode2session',{
			 method: "GET",
			 data,
			 dataType: 'json'
		  })
	const success = res.status === 200 && res.data && res.data.openid
		  if(!success){
			return {
				status: -1,
				msg: '微信登录失败'
			}
		  }
	let openId = res.data.openid
	const tokenExp = 7200000
	let time = Date()
	let tokenSecret = crypto.randomBytes(16).toString('hex')
		// 生成加密密钥
		token = jwt.encode(openId,tokenSecret)
	let userInfo = {
			openId: res.data.openid,
			nickName: event.userInfo.nickName,
			avatarUrl: event.userInfo.avatarUrl,
			gender: evnet.userInfo.gender,
			city: event.userInfo.city,
			balance: '',
			couponNum: '',
			currentValue: '',
			giftBalance: '', 
			level: '',
			pointNum: '',
			CreareTime: time,
			lastLoginTime: time
		}
	let userUpdate = {
			openId: res.data.openid,
			nickName: event.userInfo.nickName,
			avatarUrl: event.userInfo.avatarUrl,
			gender: evnet.userInfo.gender,
			city: event.userInfo.city,
			lastLoginTime: time
		}
	let userResult;
	const userInDB = await db.collection('users').where({openId}).limit(1).get()
		  if(userInDB.data && userInDB.data.length === 0){
			  userResult = await db.collection('users').add({
				  ...userInfo,
				  tokenSecret,
				  exp: Date.new() + tokenExp
			  })
		  }else{
			  userResult = await db.collection('users').where({openId})
				  .update({
					  ...userUpdate,
					  tokenSecret,
					  exp: Date.new() + tokenExp
				  })
		  }
		// 返回客户端数据
	const fields = {
			nickName: 1,
			avatarUrl: 1,
			balance: 1,
			couponNum: 1,
			currentValue: 1, 
			giftBalance: 1, 
			level: 1, 
			pointNum: 1, 
			gender: 1
		  }
	let resultOk = await db.collection('users').where({openId}).field(fields).get()
	let resultData = resultOk.data[0]
		if(userResult.id || userResult.updated === 1){
			return {
				status: 0,
				msg: '微信登录成功',
				data: resultData,
				token: token 
			}
		}else {
			return {
				status: -1,
				msg: '微信登录失败'
			}
		}
		
}